class Solution {
public:
    string addBinary(string a, string b) {
        bool carry = false;
        int iter = max(a.length(), b.length());
        int length_a = a.length();
        int length_b = b.length();
        string res;
        for (int i = 0; i < iter; i++)
        {
            bool temp_a, temp_b;
            temp_a = i >= length_a ? 0 : a[length_a - i - 1] == '1';
            temp_b = i >= length_b ? 0 : b[length_b - i - 1] == '1';
            // cout<<temp_a<<endl<<temp_b<<endl<<endl;
            if(temp_a && temp_b) 
            {
                res.insert(0, 1, carry ? '1' : '0');
                carry = true;
            }
            else if(temp_a || temp_b)
                res.insert(0, 1, carry ? '0' : '1');
            else
            {
                res.insert(0, 1, carry ? '1' : '0');
                carry = false;
            }
        }
        if(carry)
            res.insert(0, 1, '1');
        return res;
    }
};
